package com.next.aappublicapp.tasks;

import java.io.InputStream;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

public class DownloadImageListTask extends AsyncTask<String, Object, Bitmap> {
	List<DownloadImageTaskParam> downloadImageTaskParams;
	ProgressBar progressBar;

	public DownloadImageListTask(List<DownloadImageTaskParam> downloadImageTaskParams) {
		this(downloadImageTaskParams,null);
	}

	public DownloadImageListTask(List<DownloadImageTaskParam> downloadImageTaskParams,ProgressBar progressBar ) {
		Log.i("DownloadImageListTask", "Download task created");
	    this.downloadImageTaskParams = downloadImageTaskParams;
	    this.progressBar = progressBar;
	}
	protected void onPreExecute() {
		if(progressBar != null){
			progressBar.setVisibility(View.VISIBLE);
		}
	}
	protected Bitmap doInBackground(String... urls) {
	    String urldisplay;
	    for(DownloadImageTaskParam oneDownloadImageTaskParam:downloadImageTaskParams){
	    	urldisplay = oneDownloadImageTaskParam.getUrl();
		    Log.i("DownloadImageTask", "Running Download Task for url "+ urldisplay);
		    Bitmap mIcon11 = null;
		    try {
		        InputStream in = new java.net.URL(urldisplay).openStream();
		        mIcon11 = BitmapFactory.decodeStream(in);
		        publishProgress(oneDownloadImageTaskParam,mIcon11);
		    } catch (Throwable e) {
		        e.printStackTrace();
		    }
	    }
	    Log.i("DownloadImageTask", "Download Task Finished");
	    // return null to let onPostExecute know that task has been finished
	    return null;
	}
	
	protected void onProgressUpdate(Object... progress) {
        DownloadImageTaskParam downloadImageTaskParam = (DownloadImageTaskParam)(progress[0]);
        Bitmap result = (Bitmap)(progress[1]);
        downloadImageTaskParam.getImageView().setImageBitmap(result);
    }


	protected void onPostExecute(Bitmap result) {
		Log.i("DownloadImageTask", "Image Loaded");
		if(progressBar != null){
			progressBar.setVisibility(View.GONE);
		}
	}
}